<template>
	<view>
		<view class="confirm-order">
			<view class="confirm-con">
				<!-- 地址 -->
				<navigator hover-class="none" url="/pages/user_address/user_address?type=1">
					<view class="contain address" v-if="!addressId">
						<view class="row-between">
							<view class="flex1 line1 lg">请选择收货地址</view>
							<image class="icon-sm" src="/static/images/arrow_right.png"></image>
						</view>
						<view class="nr mt20 line1 muted">请选择收货地址</view>
					</view>
					<view class="contain address" v-else>
						<view class="row-between">
							<view class="flex1 line1 lg">
								<text class="mr20">{{orderInfo.address.contact}}</text>
								<text>{{orderInfo.address.telephone}}</text>
							</view>
							<image class="icon-sm" src="/static/images/arrow_right.png"></image>
						</view>
						<view class="nr mt20 line1 muted">
							地址:
							{{orderInfo.address.province}}
							{{orderInfo.address.city}}
							{{orderInfo.address.district}}
							{{orderInfo.address.address}}
						</view>
					</view>
				</navigator>
				<view class="address-bottom"></view>

				<!-- 商品信息 -->
				<view class="goods contain">
					<view>
						<view class="row">
							<view>
								<image :src="orderInfo.goods_lists[0].image"
									style="width: 160rpx; height: 160rpx;border-radius: 22rpx;" />
							</view>

							<view class="flex1 ml20" style="width: 200rpx;">
								<view class="nr mb10 line1">{{ orderInfo.goods_lists[0].name }}</view>
								<view class="xs mb10 muted">规格:{{ orderInfo.goods_lists[0].spec_value_str }}</view>
								<view class="xs muted">数量:{{ orderInfo.goods_lists[0].goods_num }}</view>
							</view>
						</view>
					</view>
					<view class="goods-date">
						<view class="goods-date-title">
							<view class="goods-date-border-right">预计起租日:</view>
							<view class="goods-date-border-left">预计归还日:</view>
						</view>
						<view class="goods-date-value">
							<view class="goods-date-border-right">{{ orderInfo.lease_start_date }}</view>
							<view class="goods-date-border-left">{{ orderInfo.lease_end_date }}</view>
						</view>
					</view>
					<view class="goods-tips">提示：此处日期为预估租期，确认收货后将自动更新为实际租期，最晚可在归还日次日前归还</view>
				</view>

				<!-- 费用明细 -->
				<view class="contain">
					<view class="row-between lg mb20">
						<view>首期应付金额</view>
						<!-- <view>¥ {{ orderInfo.order_amount.toFixed(2) }}</view> -->
						<view>¥{{ Number(orderInfo.goods_first_rent).toFixed(2) }}</view>
					</view>
					<view class="lighter row-between nr mb20" v-if="orderInfo.goods_lists[0].periods > 1">
						<view>剩余租期</view>
						<view>
							¥{{ Number(orderInfo.goods_first_rent).toFixed(2) }}*{{ orderInfo.goods_lists[0].periods }}期
						</view>
					</view>
					<view class="lighter row-between nr mb20">
						<view>总租金</view>
						<view>¥{{Number(orderInfo.total_goods_rent).toFixed(2) }}</view>
					</view>
					<view class="lighter row-between nr mb20">
						<view>配送方式</view>
						<view>{{ orderInfo.delivery_type_desc }}</view>
					</view>
					<view class="lighter row-between nr">
						<view>运费</view>
						<view>¥{{Number(orderInfo.total_shipping_price).toFixed(2) }}</view>
					</view>
				</view>
				<view class="contain">
					<view class="row-between lg mb20">
						<view>商品押金</view>
						<view>¥{{Number(orderInfo.total_deposit).toFixed(2) }}</view>
					</view>
					<view class="lighter row-between row-center nr ">
						<view class="">
							<text>信用减免</text>
							<image src="@/bundle/static/images/zhimay.png" class="zhima-my" v-if="orderInfo.is_zhima"
								mode="aspectFit"></image>
						</view>
						<view>待评估</view>
					</view>
				</view>

				<!-- 配件 -->
				<view class="contain goods-accessory" v-for="(item,index) in orderInfo.goods_accessory" :key="index">
					<view class="lg mb20">{{item.name}}</view>
					<view class="accessory-item" v-for="(item2,index2) in item.accessory_item" :key="index2">
						<view class="flex1 line1">{{ item2.name }}</view>
						<view class="row">
							<view class="mr20 accessory-item-price" v-if="Number(item2.price)!=0">¥{{item2.price}}</view>
							<view>*{{item2.num}}</view>
						</view>
					</view>
				</view>

				<!-- 备注 -->
				<view class="contain user-remark">
					<view class="lg mb20">备注</view>
					<view class="remark-input">
						<input v-model="userRemark" :clearable="false" placeholder="请输入你的备注"
							style="width: 100%;background-color: #F6F6F8;" />
					</view>
				</view>
			</view>

			<!-- 订单结算 -->
			<view class="footer bg-white fixed">
				<u-checkbox-group>
					<u-checkbox v-model="isAgreeProtocol" shape="circle">
						<view class="sm row">
							<view class="lighter">我已阅读并同意</view>
							<view class="primary" @tap.stop="openLeaseProtocol()">《租赁服务协议以及相关协议》</view>
						</view>
					</u-checkbox>
				</u-checkbox-group>
				<view class="row-between mt20">
					<view class="nr mr30">
						<view class="row">
							<text>首期应付</text>
							<view class="ml10 mt10">
								<price :content="orderInfo.order_amount.toFixed(2)" mainSize="40rpx" minorSize="24rpx"
									:isSuffix="false" :isPrefix="true" />
							</view>
						</view>
						<view>共{{orderInfo.total_num}}件</view>
					</view>
					<button class="submit-btn br60 white" hover-class="none" @tap="onSubmitOrder">
						立即下单
					</button>
				</view>
			</view>
		</view>

		<loading-view v-if="showLoading" background-color="transparent" :size="50" />
		<loading-view v-if="isFirstLoading" />


		<!-- 租赁用户协议 -->
		<u-popup v-model="showLeaseProtocol" mode="center" border-radius="20">
			<view class="protocol">
				<view class="protocol-title">租赁用户协议</view>
				<scroll-view scroll-y="true" class="protocol-content">
					<u-parse :html="protocolHtml" />
				</scroll-view>
				<view class="protocol-confirm" @tap="openLeaseProtocol()">我知道了</view>
			</view>
		</u-popup>
	</view>
</template>


<script>
	// #ifdef H5
	import alipayH5 from '../../../utils/alipayjsapi.min.js'
	// #endif
	
	import {
		prepay,
		getMnpNotice,
		getAlipayPayStatus
	} from '@/api/app';

	import {
		wxpay,
		alipay
	} from '@/utils/pay'

	import {
		payment,
		leaseBuy,
		getLeaseProtocol
	} from '@/api/lease.js'

	import {
		getOrderCoupon
	} from '@/api/order';

	export default {
		data() {
			return {
				isFirstLoading: false && true,
				showLoading: false,
				orderInfo: { // 订单信息
					address: [],
					goods_lists: [],

				},
				addressId: '', // 所选地址ID
				userRemark: '', // 留言
				payload: null, // 已选规格信息
				isAgreeProtocol: false, // 协议是否同意
				showLeaseProtocol: false, // 协议 Popup
				protocolHtml: '', // 富文本协议内容
				isZhimaOrder: false, // 是否成功生成芝麻订单
			};
		},

		methods: {
			
			//判断是否是支付环境，这里主要是判断支付宝生活号
			isAlipayEnv() {
				const userAgent = navigator.userAgent.toLowerCase();
				return userAgent.indexOf('alipayclient') > -1;
			},
			
			
			//打开协议弹窗
			openLeaseProtocol() {
				this.showLeaseProtocol = !this.showLeaseProtocol;
			},
			// 微信通知
			getAuthMsg() {
				return new Promise(resolve => {
					getMnpNotice({
						scene: 1
					}).then(res => {
						if (res.code == 1) {
							const data = res.data;
							uni.requestSubscribeMessage({
								tmplIds: data
							});
						}
						resolve();
					});
				});
			},

			//拉起芝麻免押工作台
			zhimaAlimnp(orderStr) {
				return new Promise(resolve => {
					my.tradePay({
						orderStr: orderStr,
						success: (res) => {
							console.log('success', res)
							if (res.resultCode === '9000') {
								this.isZhimaOrder = true
							}
						},
						fail: (res) => {
							console.log('fail', res)
						},
						complete: () => {
							resolve();
						}
					});
				});
			},
            //拉起芝麻免押工作台H5
			zhimaAlimnpH5(orderStr){
				return new Promise(resolve => {
					alipayH5.tradePay({
						orderStr: orderStr,
						success: (res) => {
							console.log('success', res)
							if (res.resultCode === '9000') {
								this.isZhimaOrder = true
							}
						},
						fail: (res) => {
							console.log('fail', res)
						},
						complete: () => {
							resolve();
						}
					});
				});
			},
			
			
			// 点击下单
			onSubmitOrder() {
				if (!this.isAgreeProtocol)
					return uni.showToast({
						title: '请先阅读并同意协议',
						icon: 'none'
					});
				if (!this.addressId)
					return uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});

				uni.showModal({
					title: '温馨提示',
					content: '是否确认下单?',
					confirmColor: '#FF2C3C',
					success: async res => {
						if (!res.confirm) return;

						// #ifdef MP-WEIXIN
						await this.getAuthMsg();
						// #endif

						this.orderBuyFun();
					}
				});
			},

			// 下单处理
			async orderBuyFun(password) {
				this.showLoading = true;

				const submitObj = {
					action: 'submit',
					type: 'buy_now',
					goods: {
						item_id: this.payload.goods.item_id,
						goods_num: this.payload.goods.goods_num,
						periods_id: this.payload.goods.periods_id,
					},
					address_id: this.addressId,
					remark: this.userRemark
				};

				leaseBuy(submitObj).then(async res => {
					const data = res.data;
					const code = res.code;
					const order_id = data.order_id;
					const type = data.from;
					this.showLoading = false;

					//拉起芝麻免押确认页面
					if (data.order_str.length) {
						// #ifdef MP-ALIPAY
						await this.zhimaAlimnp(data.order_str)
						// #endif
						// #ifdef H5
						// if(this.isAlipayEnv()){
							await this.zhimaAlimnpH5(data.order_str)
						// }
						
						// #endif
						
					}
					//跳转支付页面
					uni.redirectTo({
						url: `/pages/payment/payment?from=${data.from}&order_id=${data.order_id}&is_zhima_order=${this.isZhimaOrder}`
					})
				});
			},
		},


		onLoad(options) {
			const data = JSON.parse(decodeURIComponent(options.data));
			this.payload = data;

			// 选择地址
			uni.$on("selectaddress", e => {
				this.addressId = e.id
				this.orderInfo.address = e.address;
			});

			// 获取协议内容
			getLeaseProtocol().then(res => {
				if (res.code != 1) return;
				this.protocolHtml = res.data || '';
			});
		},

		onShow() {
			const data = this.payload;
			console.log(data, this.addressId, 1211);

			leaseBuy({
				...data,
				address_id: this.addressId,
				action: 'info',
				type: 'buy_now'
			}).then(res => {
				console.log(res, 666);
				if (res.code != 1) return;
				const data = res.data;
				this.orderInfo = data;
				console.log(this.orderInfo, 111);
				this.addressId = data?.address?.id || '';
			});
		},

		onUnload() {
			uni.$off("selectaddress");
		},

	}
</script>
<style lang="scss">
	.confirm-order .confirm-con {
		overflow: hidden;
		padding-bottom: calc(126rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.confirm-order .contain {
		margin: 20rpx 20rpx 0;
		background-color: #fff;
		overflow: hidden;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}

	.address-bottom {
		margin: 0 10px;
		height: 4rpx;
		background-image: url('/static/images/icon_address_bottom_img.png');
		background-size: 100%;
	}

	.goods-date {
		border-radius: 16rpx;
		line-height: 64rpx;
		text-align: center;
		font-size: 24rpx;
		overflow: hidden;
		margin: 32rpx 0;

		.goods-date-title {
			display: flex;
			background-color: #EFEFEF;
		}

		.goods-date-border-right {
			border-right: 1rpx solid #fff;
			flex: 1;
		}

		.goods-date-border-left {
			border-left: 1rpx solid #fff;
			flex: 1;
		}

		.goods-date-value {
			display: flex;
			background-color: #FBFBFD;
			font-weight: 500;
		}
	}

	.goods-tips {
		border-radius: 12px;
		padding: 8px 7px;
		background-color: #C38B611A;
		color: #C38B61;
		font-size: 24rpx;
	}

	.accessory-item {
		padding: 20rpx 30rpx;
		margin-top: 20rpx;
		border-radius: 16rpx;
		background-color: #F6F6F8;
		color: #00000099;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.accessory-item-price {
			opacity: .5;
			text-decoration: line-through;
		}
	}

	.remark-input {
		padding: 10rpx 30rpx;
		border-radius: 16rpx;
		background-color: #F6F6F8;
		color: #00000099;
		font-size: 28rpx;
	}

	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.confirm-order .footer {
		box-sizing: content-box;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding-left: 20rpx;
		padding-right: 20rpx;
		padding-top: 20rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}


	.confirm-order .pay-way .title {
		padding: 20rpx 24rpx;
	}

	.confirm-order .pay-way .radio-group .item {
		height: 120rpx;
		padding: 0 24rpx;
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .goods>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.submit-btn {
		background-color: #2482EE !important;
		padding: 0 80rpx !important;
		height: 80rpx !important;
		line-height: 80rpx !important;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.goods .shop-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #F2F2F2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}


	.protocol {
		display: flex;
		flex-direction: column;
		width: 88vw;
		height: 88vh;
		padding: 20rpx;
		background-color: #FFFFFF;
	}

	.protocol-title {
		padding: 20rpx 0;
		font-size: 32rpx;
		font-weight: 500;
		text-align: center;
		color: #333333;
	}

	.protocol-content {
		flex: 1;
		overflow: scroll;
	}

	.protocol-confirm {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 72rpx;
		border-radius: 50px;
		margin-top: 20rpx;
		font-size: 32rpx;
		background-color: #24A3FF;
		color: #FFFFFF;
	}

	.zhima-my {
		width: 120rpx;
		height: 40rpx;
		margin-left: 10rpx;
		vertical-align: bottom;
	}
</style>